<?php

namespace App\Library\Payment\Alipay;

use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use App\Library\Payment\BasePayment;

/**
 *
 */
class BaseAlipayApi extends BasePayment
{
	protected static string $serverUrl;
	protected static string $notifyUrl;
	protected static string $appId;
	protected static string $merchantPrivatePath;

	// 证书模式时设置
//	protected static string $certPath;
//	protected static string $rootCertPath;
//	protected static string $merchantCertPath;

	protected static string $alipayPublicPath;

	public function __construct()
	{
		self::_init();
	}


	/**
	 * 初始化数据
	 * @return void
	 */
	public static function _init()
	{
		self::$serverUrl = config('alipay.serverUrl');
		self::$notifyUrl = config('alipay.notifyUrl');
		self::$appId = config('alipay.appId');
		self::$merchantPrivatePath = config('alipay.merchantPrivatePath');
		// 证书模式时设置
		// self::$certPath = config('alipay.certPath');
		// self::$rootCertPath = config('alipay.rootCertPath');
		// self::$merchantCertPath = config('alipay.merchantCertPath');
		self::$alipayPublicPath = config('alipay.alipayPublicPath');
	}

	/**
	 * @return Config
	 */
	protected function getOptions(): Config
	{
		$options = new Config();
		$options->protocol = 'https';
		$options->gatewayHost = self::$serverUrl;
		$options->signType = 'RSA2';
		$options->appId = self::$appId;

		// 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
		$options->merchantPrivateKey = rtrim(file_get_contents(self::$merchantPrivatePath));
		$options->alipayPublicKey = rtrim(file_get_contents(self::$alipayPublicPath));
		// 证书模式时设置
		// $options->alipayCertPath = self::$certPath;
		// $options->alipayRootCertPath = self::$rootCertPath;
		// $options->merchantCertPath = self::$merchantCertPath;

		//可设置异步通知接收服务地址（可选）
		$options->notifyUrl = self::$notifyUrl;

		return $options;
	}

	/**
	 * 批量设置额外参数
	 * @param array $params
	 * @return void
	 * @var int $params timeExpire 过期时间时间戳
	 * @var array $params params 额外参数【里面具体内容不关系，业务段自己定义，回调时会返回】
	 */
	protected function setBatchOptional(array $params)
	{
		$batchOptional = [];
		// 绝对超时过期时间
		if (!empty($params['timeExpire'])) {
			$batchOptional['time_expire'] = date('Y-m-d H:i:s', $params['timeExpire']);
		}
		// 额外参数
		if (!empty($params['params'])) {
			$passbackParams = urlencode(http_build_query($params['params']));
			$batchOptional['passback_params'] = $passbackParams;
		}

		Factory::payment()->app()->batchOptional($batchOptional);
	}
}